package com.business_clean.ui.activity.project;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.callback.OnDialogSelectListener;
import com.business_clean.app.callback.OnDialogTimePickerListener;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.ext.LoadingDialogExtKt;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.ChoosePicUtil;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.app.weight.dialog.CustomTimePickerPopup;
import com.business_clean.data.mode.custom.CompanyBaseEntity;
import com.business_clean.data.mode.custom.CustomMangerList;
import com.business_clean.data.mode.custom.WorkPostData;
import com.business_clean.data.mode.format.FormatChildItemList;
import com.business_clean.data.mode.job.JobEntity;
import com.business_clean.data.mode.job.JobListEntity;
import com.business_clean.data.mode.project.ProjectCompanyDetailEntity;
import com.business_clean.data.mode.roster.RosterList;
import com.business_clean.databinding.ActivityAddProjectCompanBinding;
import com.business_clean.ui.activity.PreviewPhotoActivity;
import com.business_clean.ui.activity.custom.CustomManagerActivity;
import com.business_clean.ui.activity.depart.QuickDepartActivity;
import com.business_clean.ui.activity.format.FormatActivity;
import com.business_clean.ui.activity.personnel.SelectPersonnelActivity;
import com.business_clean.ui.adapter.GridImageAdapter;
import com.business_clean.ui.adapter.custom.ProjectWorkAdapter;
import com.business_clean.viewmodel.request.ProjectManagerViewModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import me.hgj.mvvmhelper.ext.AppExtKt;
import me.hgj.mvvmhelper.ext.LogExtKt;

public class AddCompanyProjectActivity extends BaseActivity<ProjectManagerViewModel, ActivityAddProjectCompanBinding> {

    private String[] strings = {"拍照", "相册"};

    private GridImageAdapter mAdapter;

    private ProjectWorkAdapter mWorkAdapter;

    private String project_cat_id;//子业态ID

    private String project_uuid;
    private String custom_uuid;
    final int MAX_CHARACTERS = 150; // 最大字符数限制

    private String manager_user_uuid;

    private ArrayList<String> works = new ArrayList<>();//记录 岗位

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        if (getIntent() != null && getIntent().getExtras() != null) {
            project_uuid = getIntent().getExtras().getString("uuid");
            mViewModel.requestProjectMangerDetails(project_uuid);
            mDatabind.tabbar.setTitle("编辑项目");
        }
        mAdapter = new GridImageAdapter(this);
        mAdapter.setSelectMax(9);
        mDatabind.upload.recyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        mDatabind.upload.recyclerview.addItemDecoration(new MyGridSpacingItemDecoration(4, SizeUtils.dp2px(10), false));
        mDatabind.upload.recyclerview.setAdapter(mAdapter);
        //工作岗位编制
        mWorkAdapter = new ProjectWorkAdapter();
        mDatabind.recyclerviewPost.setLayoutManager(new LinearLayoutManager(this));
        mDatabind.recyclerviewPost.setAdapter(mWorkAdapter);
        //其他的设置
        mDatabind.withProjectRoomSize.setInputNumber();
        mViewModel.getJobList();

        mDatabind.withEndNumber.setInputNumber();


        mDatabind.withProjectNameSimple.getInputEdit().setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});

        mDatabind.withProjectNameSimple.getLlLayout().setMinimumHeight(SizeUtils.dp2px(30));
        mDatabind.withProjectRegionalManager.getLlLayout().setMinimumHeight(SizeUtils.dp2px(30));

        mDatabind.upload.tvBaseUploadTitle.setText("合同照片");
    }

    @Override
    public void initObserver() {
        //监听选择大区经理
        App.appViewModelInstance.getSelectedPersonnel().observe(this, new Observer<List<RosterList>>() {
            @Override
            public void onChanged(List<RosterList> rosterLists) {
                if (rosterLists.size() > 0) {
                    manager_user_uuid = rosterLists.get(0).getUuid();
                    mDatabind.withProjectRegionalManager.setTvRightText(rosterLists.get(0).getUser_name());
                }
            }
        });
        //监听选择客户
        App.appViewModelInstance.getSelectCustomMangerList().observe(this, new Observer<CustomMangerList>() {
            @Override
            public void onChanged(CustomMangerList customMangerList) {
                if (customMangerList != null) {
                    custom_uuid = customMangerList.getUuid();
                    mDatabind.withProjectCompnay.setTvRightText(customMangerList.getCustom_name());
                }
            }
        });
        //坚挺业态n
        App.appViewModelInstance.getSelectedFormat().observe(this, new Observer<FormatChildItemList>() {
            @Override
            public void onChanged(FormatChildItemList formatChildItemList) {
                project_cat_id = formatChildItemList.getId();
                mDatabind.withProjectBusiness.setTvRightText(formatChildItemList.getCat_name());
            }
        });

        mDatabind.remark.editRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int currentCount = s.length();
                if (currentCount > MAX_CHARACTERS) {
                    // 如果超出限制，则阻止用户输入并截断字符串
                    String truncatedText = s.toString().substring(0, MAX_CHARACTERS);
                    mDatabind.remark.editRemark.setText(truncatedText);
                    mDatabind.remark.editRemark.setSelection(MAX_CHARACTERS); // 将光标移动到末尾
                    currentCount = MAX_CHARACTERS; // 更新当前字符数量为最大字符限制
                }
                mDatabind.remark.tvEditNumber.setText(currentCount + "/" + MAX_CHARACTERS);
            }
        });
    }

    @Override
    public void onBindViewClick() {
        //选择大区经理
        mDatabind.withProjectRegionalManager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("multiple", 1);
                bundle.putInt("role_id", 6);
                bundle.putInt("is_head_office", 1);
                ActivityForwardUtil.startActivity(SelectPersonnelActivity.class, bundle);
            }
        });
        //添加岗位
        mDatabind.butAddProjectWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (works != null && works.size() > 0) {
                    CommonUtils.showDialogWheelSingleList(AddCompanyProjectActivity.this, "请选择岗位", works, "", new OnDialogSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            if (mWorkAdapter.checkRepeatData(mViewModel.getJobManger().getValue().getList().get(position))) {
                                ToastUtil.show("您已选择该岗位，请勿重复选择");
                            } else {
                                mWorkAdapter.addData(mViewModel.getJobManger().getValue().getList().get(position));
                            }
                        }
                    });
                } else {
                    mViewModel.getJobList();
                }
            }
        });

        //相册列表
        mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
//                Bundle bundle = new Bundle();
//                bundle.putString("url", mAdapter.getData().get(position));
//                ActivityForwardUtil.startActivity(PreviewPhotoActivity.class);
            }

            @Override
            public void openPicture() {
                showBottomSelectedPic();
            }
        });

        //提交
        mDatabind.buttom.butBase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mDatabind.withProjectName.getInputText())) {
                    ToastUtil.show("请输入项目名称");
                    return;
                }
                if (TextUtils.isEmpty(mDatabind.withProjectNameSimple.getInputText())) {
                    ToastUtil.show("请输入项目简称");
                    return;
                }

                if (TextUtils.isEmpty(mDatabind.withProjectCompnay.getTvRight())) {
                    ToastUtil.show("请选择客户公司");
                    return;
                }
                if (TextUtils.isEmpty(mDatabind.withProjectBusiness.getTvRight())) {
                    ToastUtil.show("请选择业态公司");
                    return;
                }
                if (TextUtils.isEmpty(mDatabind.withProjectRoomSize.getInputText())) {
                    ToastUtil.show("请选择服务面积公司");
                    return;
                }

                if (TextUtils.isEmpty(mDatabind.withStartDate.getTvRight())) {
                    ToastUtil.show("请选择合作开始日期");
                    return;
                }
                if (TextUtils.isEmpty(mDatabind.withEndDate.getTvRight())) {
                    ToastUtil.show("请选择合同结束日期");
                    return;
                }
                if (TextUtils.isEmpty(mDatabind.withEndNumber.getInputText())) {
                    ToastUtil.show("请选择合同人数");
                    return;
                }
                if (mWorkAdapter.getData().size() == 0) {
                    ToastUtil.show("至少需要添加1个岗位");
                    return;
                }
                HashMap<String, String> hashMap = new HashMap<>();
                if (!TextUtils.isEmpty(project_uuid)) {
                    hashMap.put("project_uuid", "" + project_uuid);
                }
                hashMap.put("project_name", "" + mDatabind.withProjectName.getInputText());
                if (custom_uuid != null) {
                    hashMap.put("custom_uuid", "" + custom_uuid);
                }
                if (!TextUtils.isEmpty(project_cat_id)) {
                    hashMap.put("project_cat_id", "" + project_cat_id);
                }
                if (!TextUtils.isEmpty(manager_user_uuid)) {
                    hashMap.put("manager_user_uuid", "" + manager_user_uuid);
                }

                hashMap.put("project_short_name", "" + mDatabind.withProjectNameSimple.getInputText());
                hashMap.put("square", "" + mDatabind.withProjectRoomSize.getInputText());
                hashMap.put("remark", "" + mDatabind.remark.editRemark.getText().toString());
                hashMap.put("contract_pic", JSON.toJSONString(mAdapter.getData()));
                hashMap.put("job_info_list", JSON.toJSONString(mWorkAdapter.getData()));
                hashMap.put("start_time", "" + mDatabind.withStartDate.getTvRight());
                hashMap.put("end_time", "" + mDatabind.withEndDate.getTvRight());
                hashMap.put("contract_human_num", "" + mDatabind.withEndNumber.getInputText());
                mViewModel.saveProject(hashMap);
            }
        });

        //合作开始日期
        mDatabind.withStartDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar defInstance = Calendar.getInstance();
                if (!TextUtils.isEmpty(getMDatabind().withStartDate.getTvRight())) {
                    defInstance.setTime(TimeUtils.string2Date(getMDatabind().withStartDate.getTvRight(), "yyyy-MM-dd"));
                }
                CommonUtils.showDialogTimePickerView(AddCompanyProjectActivity.this, "合同开始日期", defInstance, 2000, 2099, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        mDatabind.withStartDate.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                });
            }
        });
        //合作结束日期
        mDatabind.withEndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar defInstance = Calendar.getInstance();
                if (!TextUtils.isEmpty(getMDatabind().withEndDate.getTvRight())) {
                    defInstance.setTime(TimeUtils.string2Date(getMDatabind().withEndDate.getTvRight(), "yyyy-MM-dd"));
                }
                CommonUtils.showDialogTimePickerView(AddCompanyProjectActivity.this, "结束开始日期", defInstance, 2000, 2099, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        mDatabind.withEndDate.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                });
            }
        });
        //客户公司
        mDatabind.withProjectCompnay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("isSelected", true);
                ActivityForwardUtil.startActivity(CustomManagerActivity.class, bundle);
            }
        });
        //项目业态
        mDatabind.withProjectBusiness.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("project_cat_id", project_cat_id);
                ActivityForwardUtil.startActivity(FormatActivity.class, bundle);
            }
        });
    }

    /**
     * 打开相册，让选择
     */
    private void showBottomSelectedPic() {
        CommonUtils.showBottomListWith(this, 20, "", strings, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                switch (position) {
                    case 0:
                        ChoosePicUtil.openCameraTake(AddCompanyProjectActivity.this);
                        break;
                    case 1:
                        ChoosePicUtil.openAlbum(AddCompanyProjectActivity.this, 9 - mAdapter.getData().size());
                        break;
                }
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getProjectState().observe(this, new Observer<CompanyBaseEntity>() {
            @Override
            public void onChanged(CompanyBaseEntity data) {
                ToastUtil.show("操作成功");
                App.appViewModelInstance.getRefreshProjectManagerList().setValue(true);
                if (TextUtils.isEmpty(project_uuid)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("uuid", "" + data.getUuid());
                    ActivityForwardUtil.startActivity(CompanyProjectDetailActivity.class, bundle);
                }
                AppExtKt.finishActivity(AddCompanyProjectActivity.class);
            }
        });

        mViewModel.getProjectCompanyDetailEntity().observe(this, new Observer<ProjectCompanyDetailEntity>() {
            @Override
            public void onChanged(ProjectCompanyDetailEntity projectCompanyDetailEntity) {
                fillData(projectCompanyDetailEntity);
            }
        });

        mViewModel.getJobManger().observe(this, new Observer<JobEntity>() {
            @Override
            public void onChanged(JobEntity jobEntity) {
                for (JobListEntity list : jobEntity.getList()) {
                    works.add(list.getJob_name());
                }
                if (!TextUtils.isEmpty(project_uuid)) {
                    return;
                }
                for (int i = 0; i < jobEntity.getList().size(); i++) {
                    if (jobEntity.getList().get(i).getJob_name().equals("保洁员")) {//要默认添加保洁员
                        mWorkAdapter.addData(jobEntity.getList().get(i));
                        break;
                    }
                }
            }
        });
    }

    private void fillData(ProjectCompanyDetailEntity data) {
        if (data != null) {
            mDatabind.withProjectName.setInputText(data.getProject_name());
            mDatabind.withProjectNameSimple.setInputText(data.getProject_short_name());
            mDatabind.withProjectCompnay.setTvRightText(data.getCustom_name());
            project_cat_id = data.getProject_cat_id();
            custom_uuid = data.getCustom_uuid();
            mDatabind.withProjectBusiness.setTvRightText(data.getProject_cat_parent_name());
            mDatabind.withProjectRoomSize.setInputText(data.getSquare());
            mDatabind.remark.editRemark.setText(data.getRemark());
            mDatabind.withStartDate.setTvRightText(data.getStart_time());
            mDatabind.withEndDate.setTvRightText(data.getEnd_time());
            mDatabind.withEndNumber.setInputText(data.getContract_human_num());
            manager_user_uuid = data.getManager_user_uuid();
            mDatabind.withProjectRegionalManager.setTvRightText(data.getManager_user_name());


            for (String url : data.getContract_pic()) {
                mAdapter.addItemData(url);
            }
            for (JobListEntity jobList : data.getJob_info_list()) {
                mWorkAdapter.addData(jobList);
            }
        }
    }


    private void uploadPictures(ArrayList<LocalMedia> result) {
        LoadingDialogExtKt.showLoadingExt(this, "上传中");
        ArrayList<String> strings1 = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            strings1.add(result.get(i).getCompressPath());
        }
        UploadFileHelper.getInstance().uploadFiles(this, strings1, UploadFileHelper.PATH_HEADER_CUSTOM, new UploadFileHelper.UploadListener() {
            @Override
            public void onUploadSuccess(String url) {
                mAdapter.addItemData(url);
                LoadingDialogExtKt.dismissLoadingExt(AddCompanyProjectActivity.this);
            }

            @Override
            public void onUploadFailed(String errorMessage) {
                LogExtKt.logE("失败  ： " + errorMessage, "七牛云上传");
                ToastUtil.show("上传失败，请重新上传");
                LoadingDialogExtKt.dismissLoadingExt(AddCompanyProjectActivity.this);
            }

            @Override
            public void onUploadProgress(int progress) {

            }


        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST || requestCode == PictureConfig.REQUEST_CAMERA) {//相册
                ArrayList<LocalMedia> result = PictureSelector.obtainSelectorList(data);
                Log.e("", "onActivityResult " + result.get(0).getCompressPath());
                uploadPictures(result);
            }
        } else if (resultCode == RESULT_CANCELED) {
            Log.e("", "onActivityResult PictureSelector Cancel");
        }
    }


}